package Servlet;

import Service.CaptchaStoreService;
import utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Su
 * @Date 2025/4/30 16:16
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/auth/captcha")//原来图片验证码是为了防人机 妈呀现在才知道
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 生成验证码
        CaptchaUtil.Captcha captcha = CaptchaUtil.generateCaptcha();

        // 存储到会话
        HttpSession session = req.getSession();
        CaptchaStoreService.storeCaptcha(session.getId(), captcha.getText());

        // 返回图片
        resp.setContentType("image/jpeg");
        resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Expires", "0");

        try (ServletOutputStream out = resp.getOutputStream()) {
            out.write(captcha.getImageData());
        }


        //** ********请求发送验证码太多次，在doget后面增加一个
    }       //protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    //String ip = req.getRemoteAddr();
    //if (rateLimiter.exceedsLimit(ip)) {
    //      resp.sendError(429, "请求过于频繁");
    //    return;

    //******设置一个什么防止验证码缓存，验证码缓存可能会导致被恶意登录注册

}

